<template>
  <div class="home">

    <el-container style="height: calc(100vh - 60px)">
      <el-header height="60px">
        <div>
          <el-row :gutter="4">
           <el-col :span="2">
               <span>目标jar包</span> 
            </el-col>
            <el-col :span="7">
              <el-input  v-model="jarPath" @change="jarpathChange"></el-input>
            </el-col>

            <el-col :span="2" ><div style="text-align: left">
                <el-button @click="reload">确定</el-button>
              </div>
              </el-col >
            <el-col :span="4">
              <el-input  @change="jarpathChange"  v-model="formData.ip"  > <template slot="prepend">ip:</template> </el-input>
            </el-col>
            <el-col :span="4">
              <el-input  @change="jarpathChange"  v-model="formData.port"  > <template slot="prepend">端口:</template> </el-input>
            </el-col>
            <el-col :span="4">
              <!-- <el-input  @change="jarpathChange"  v-model="formData.pid"  > <template slot="prepend">进程id:</template> </el-input> -->
              <el-select v-model="formData.pid" popper-class="selectWid" placeholder="请选择">
                  <el-option
                    v-for="item in listVm"
                    :key="item.id"
                    :label="item.displayName"
                    :value="item.id">
                  </el-option>
                 
                </el-select>

            </el-col>

          </el-row>
        </div>
      </el-header>
      <el-container style="height: calc(100vh - 340px)">
        <el-aside width="300px">
          <div v-infinite-scroll style="overflow: auto">
            <left-tree
              ref="leftTree"
              :jarPath="jarPath"
              @showClassCode="showClassCode($event)"
            ></left-tree>
          </div>
        </el-aside>

        <el-main>
          <!-- <router-view/> -->
          
              <el-row>
              <el-col :span="12">
                <label>代码块</label>
              </el-col>
              <el-col :span="12">
                <label>修改信息</label>
              </el-col>
              </el-row>

            <div>
            <el-row>
              <el-col :span="12">
                <el-tabs v-model="activeName" @tab-click="handleTabClick">
                  <el-tab-pane label="代码块" name="1">
                    <el-row>
                     
                     <el-col :span="24">
                    <div v-if="showType == 1">
                       <el-button  type="primary" style="position: absolute; top: 0;right: 0; z-index: 9;" icon="el-icon-edit"   @click="edit(1)"> </el-button>
                      <show-code ref="edit1"  @currentCode="currentCode"  :code="classCode" @change="codeChange"  ></show-code> 
                       
                  </div>
                  <div v-else>
                    <el-button  type="primary" style="position: absolute; top: 0;right: 0; z-index: 9;" icon="el-icon-edit"   @click="edit(2)"> </el-button>
                      <show-code ref="edit2" @currentCode="currentCode" :code="methodCode"></show-code>
                  </div>
                     </el-col>
                  </el-row>

                  </el-tab-pane>
                  <el-tab-pane label="定时任务补偿" name="2">定时任务补偿</el-tab-pane>
                </el-tabs>

                <!-- <div class="formCroll">
                  <el-row> 
                     <el-col :span="24">
                    <div v-if="showType == 1">
                      <show-code  :code="classCode" @change="codeChange"  ></show-code>
                  </div>
                  <div v-else>
                    
                      <show-code  :code="methodCode"></show-code>
                  </div>
                     </el-col>
                  </el-row>
                </div> -->
              </el-col>
              <el-col
                :span="12"  
              >
              <div class="formCroll">
                <!-- <label>操作信息</label> -->
                <el-form
                  ref="form"
                  :model="formData"
                   class="form"
                  label-width="100px"
                >
                  <el-row style="padding: 5px">
                    <el-col :span="8">
                      <el-form-item label="类型">
                        <el-select
                          v-model="formData.type"
                          @change="typeChange"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="item in typeOptions"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="16">
                      <el-form-item label="操作类型">
                        <el-select
                          multiple
                          v-model="optType"
                          @change="optTypeChange"
                          clearable
                          placeholder="请选择活动区域"
                        >
                          <el-option
                            v-for="item in OptTypeOptions"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <!-- <el-row style="padding: 5px">
                    <el-col :span="8" v-if="paramsShow"> -->
                      <el-form-item label="参数" v-if="paramsShow"    >
                        <el-input v-model="formData.params" placeholder="请输入参数,多个参数使用逗号隔开"></el-input>
                      </el-form-item>
                    <!-- </el-col>
                    <el-col :span="8"> -->
                      <el-form-item label="局部变量"  v-if="paramsShow2"   >
                        <el-input v-model="formData.localVars" placeholder="请输入参数,多个参数使用逗号隔开"></el-input>
                      </el-form-item>
                    <!-- </el-col>
                    <el-col :span="8"> -->
                      <el-form-item label="全局变量"   v-if="paramsShow3"   >
                        <el-input v-model="formData.globalVars" placeholder="请输入参数,多个参数使用逗号隔开"  ></el-input>
                      </el-form-item>
                    <!-- </el-col> -->
                    <!-- </el-row> -->
                      <el-form-item label="引用包名"     > 
                        <el-input v-model="formData.importPackages" placeholder="请输入应用到的包名,多个包使用逗号隔开"  ></el-input>
                      </el-form-item>

                      <el-form-item label="目标:"  > 
                        <!-- <el-input v-model="formData.targetMethod" placeholder="" disabled ></el-input> -->
                        <label> 包名: {{formData.packageName}} &ensp; </label>
                        <label> 类名:  {{formData.className}} &ensp; </label>
                        <label> 方法: {{targetMethod.name}}  </label>
                      </el-form-item>

                      <el-form-item label="代码块"   v-if="formData.type==2 ||formData.type== 3 "   >
            
                        <el-input type="textarea" placeholder="请输入java代码" :rows="3" v-model="formData.params4"></el-input>
                      </el-form-item>
                  <el-row>
                    <el-col :span="24" style="text-align: center">
                      <el-button type="primary"  @click="submit">确定</el-button>
                      <el-button type="warning" @click="recover">恢复</el-button>
                    </el-col>
                  </el-row>
                </el-form>


              </div>

              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
      <el-footer height="200px" width="100%" style="padding:0 10px">
        <el-tabs v-model="activeName2" @tab-click="handleTabClick">
          <el-tab-pane label="执行日志" name="1">
                   <div>
                        <el-button size="small" type="primary" icon="el-icon-delete" style="position: absolute; top: 0; right: 5px; z-index: 9;" @click="clearMsg(2)" > </el-button>
                       <el-input
                          class="controlMsg"
                          id="consoleCode"
                          type="textarea"
                          :rows="6"
                           resize="none"
                          placeholder="这里展示消息2"
                          readonly
                          v-model="controlTab2"
                        >
                        </el-input>
                     </div>
            </el-tab-pane>
            <el-tab-pane label="方法日志" name="2">
                    <div>
                       <el-button  size="small" type="primary" icon="el-icon-delete" style="position: absolute; top: 0; right: 5px; z-index: 9;" @click="clearMsg(1)" ></el-button>
                        <el-input
                          class="controlMsg"
                          id="consoleCode"
                          type="textarea"
                          :rows="6"
                          resize="none"
                          placeholder="这里展示消息"
                          readonly
                          v-model="controlTab1"
                        >
                        </el-input>
                     </div>
            </el-tab-pane>
            
        </el-tabs>
        <!-- <div>
          <el-input
            class="controlMsg"
            id="consoleCode"
            type="textarea"
            :rows="8"
            resize="none"
            placeholder="这里展示消息"
            readonly
            v-model="socketmsg"
          >
          </el-input>
        </div> -->
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import leftTree from "../components/leftTree";
import showCode from "../components/code";
export default {
  name: "Home",
  components: {
    leftTree,
    showCode
  },
  data() {
    return {
      jarPath:"E:\\java_agent_demo-master\\main\\target\\main-1.0-SNAPSHOT.jar",
      formData: {
            "pid": "",
            "ip": "127.0.0.1",
            "port": 8888,
            "className": "AgentTarget",
            "createProxy": false,
            "importPackages": "",
            "jarFile": "D:\\bytespy\\bytespy-spy\\target\\bytespy-spy-1.0.0-jar-with-dependencies.jar",
            "lineCode": "System.out.println(this.getCmd());",
            "methodBody": "public String getCmd () { return \"test\"; }",
            "methodName": "",
            "packageName": "com.chl.demo.agent.target",         
            "recover": false,
            "signature": "(Ljava/lang/String;I)Ljava/lang/String;",
            "type": "1",
            "operator": "",
            "globalVars": "num",
            "localVars": ""
          },
      optType:[],
      targetMethod:'',
      // num: '',
      activeName:'1',
      activeName2:'1',
      
      filterText: "",
      classCode: "",
      methodCode: "",
      socketmsg: "",
      controlTab1:"",
      controlTab2:"",
      showType: "1",
      typeOptions: [],
      OptTypeOptions: [],
      listVm: [],

      paramsShow: true,
      paramsShow2: true,
      paramsShow3: true,

      methodChanged:{},
    }
  },
 
  mounted() {
    this.initWebSocket();
    this.getlistVm();
    this.getType();
    // this.handleTextareaInput('')
  },
  methods: {
    codeChange(val){
      console.log(val)
    },
    showClassCode(event) {
      console.log(event);
      if (event.type) {
        this.showType = event.type;
      }
      if (event.type == 1) {
        this.getClassCodeBlock(event.packageName, event.className);
      }
      if (event.type == 2) {
        this.getMethodCode(
          event.packageName,
          event.className,
          event.methodName,
          event.params
        );
        this.targetMethod= event //.packageName+'.'+event.className+'.'+event.name
        this.formData.methodName = event.methodName;
        this.formData.className = event.className;
        this.formData.packageName = event.packageName;
        this.formData.signature = event.signature;
      }
    },
    jarpathChange(e) {
      console.log(e);
      this.listVm.filter(value=>{
        return e.indexOutOf(value.displayName)!=-1
      })

    },
    submit(){
      var that = this;
      console.log(this.optType.join(","))
      
      let operator =  this.optType.join(",")
      var params = this.formData;
      params.operator=  operator 
      // params.recover = "true"

      // console.log(params )
      // this.$axios
      //   .post('/bytespy/api/v1/exec',params, {
      //       headers:{
      //         'Content-Type': 'application/json;charset=UTF-8',
      //       }
      //     })
      //   .then((res) => {
          // if (res.code == "0") {
              params.recover= false
              that.$axios.post('/bytespy/api/v1/exec',params, {
                    headers:{
                      'Content-Type': 'application/json;charset=UTF-8',
                    }
                }).then((res)=>{
                    if (res.code == "0") {
                      this.$message({
                      message: '执行成功',
                      type: 'success'
                      });
                    }
                });


            // this.$message({
            //   message: '执行成功',
            //   type: 'success'
            // });

        //   } 
        // })
        // .catch((err) => {
        //   console.log(err);
        // });
      
    },
    recover(){
      
      var params = this.formData;
      let operator =  this.optType.join(",")
      params.operator=  operator 

      params.recover = true
      console.log(params )
      this.$axios
        .post('/bytespy/api/v1/exec',params, {
            headers:{
              'Content-Type': 'application/json;charset=UTF-8',
            }
          })
        .then((res) => {
            if (res.code == "0") {
              this.$message({
              message: '恢复成功',
              type: 'success'
            });
          } 
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getClassCodeBlock(packageName, className) {
      var that = this;
      this.classCode = "";
      this.$axios
        .get("/bytespy/api/v1/getClassCodeBlock", {
          params: {
            packageName: packageName,
            className: className,
          },
        })
        .then((data) => {
          if (data.code == "0") {
            that.classCode = data.data;
          } else {
            that.classCode = "";
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getMethodCode(packageName, className, methodName, params) {
      var that = this;
      this.methodCode = "";
      this.$axios
        .get("/bytespy/api/v1/getMethodCodeBlock", {
          params: {
            packageName: packageName,
            className: className,
            methodName: methodName,
            params: params,
          },
        })
        .then((data) => {
          if (data.code == "0") {
            that.methodCode = data.data;
          } else {
            that.methodCode = [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    reload() {
      this.$refs.leftTree.reloadTree();
    },
    initWebSocket() {
      var that = this;
      if (window.WebSocket) {
        let ws = new WebSocket("ws://192.168.31.126:17010/bytespy/ws/3"); // 建立连接
        this.ws = ws;
        // 服务器连接成功
        ws.onopen = function () {
          console.log("连接成功");
          ws.send("hello"); // 给后台发消息
          this.heartbeat(); // 开启心跳
        };
        // 服务器连接关闭
        ws.onclose = function () {
          console.log("连接关闭");
        };
        // 服务器连接出错
        ws.onerror = function () {
          console.log("连接出错");
        };
        // 解析信息
        ws.onmessage = function (e) {
          console.log(e, "接收数据");
          var json  =  JSON.parse(e.data)
          console.log(json)
          if(json.type == 'methodLog'){
            that.controlTab1 = that.controlTab1.concat( json.msg )
          }else if(json.type==''){
             that.controlTab2 = that.controlTab2.concat( json.msg )
          }
          
         
          const textarea = document.getElementById("consoleCode");
          textarea.scrollTop = textarea.scrollHeight;

        };

        //心跳
        ws.heartbeat = function () {
          setInterval(() => {
            console.log("心跳");
            that.ws.send("心跳");
          }, 60000);
        };
      }
      // 心跳
    },
    getType() {
      var that = this;
      this.$axios
        .post("/bytespy/api/v1/type")
        .then((data) => {
          if (data.code == "0") {
            that.typeOptions = data.data;
            that.getOptType(data.data[0].type)
          } else {
            that.typeOptions = [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getOptType(type) {
      console.log(type + " sss");
      var that = this;
      this.$axios
        .post("/bytespy/api/v1/operator", { type: type })
        .then((data) => {
          if (data.code == "0") {
            that.OptTypeOptions = data.data;
          } else {
            that.OptTypeOptions = [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    typeChange(val) {
      this.formData.optType = "";
      this.OptTypeOptions = [];
      if (!val) return;
      this.getOptType(val);
    },
    optTypeChange(val) {
      console.log(val);
    },
    getlistVm() {
      var that = this;
      this.$axios.get("/bytespy/api/v1/listVm",{}).then((data) => {
            if(data.code=='0'){
                that.listVm = data.data;
                that.listVm.forEach(item=>{
                   if(item.displayName.indexOf(".jar")>-1 && item.displayName.length>0 && item.displayName.length<50 ){
                     that.formData.pid=item.id;
                   }
                })
            }
      }).catch(err=>{
          console.log(err)
      });
    },
    handleTabClick(){

    },
    edit(val){
      console.log(val)
      this.$refs['edit'+val].editCode();
    },
    clearMsg(val){
        if(val===1){
          this.controlTab1='';
        }else{
          this.controlTab2='';
        }
         
    },
    currentCode(val){
      console.log(val)
    }

  },
};
</script>
<style>
.home {
  height: calc(100vh - 60px);
}
 .formCroll {
   height: calc(100vh - 380px);
   overflow: auto;
   padding-right: 10px;
 }

.el-header,
.el-footer {
  /* background-color: #B3C0D1; */
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-footer {
  height: 200px;
}

.controlMsg {
  line-height: 4;
  white-space:pre-wrap;
}

.el-aside {
  height: 100vh - 320px;
  /* background-color: #D3DCE6; */
  color: #333;
  text-align: center;
  padding: 5px;

  /* overflow: auto; */
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: left;
  padding: 5px;
  /* line-height: 160px; */
  height: 100vh - 380px;
}

.code {
  height: calc(100vh - 440px);
  min-height: 30px;
  font-family: "Courier New", Courier, monospace;
  overflow: auto;
  padding: 0.5em;
  margin-top: 1em;
  margin-bottom: 1em;
  line-height: 1.42857;
  word-break: break-all;
  word-wrap: break-word;
  color: rgba(51, 51, 51, 1);
  border-top: 1px solid rgba(204, 204, 204, 1);
  border-right: 1px solid rgba(204, 204, 204, 1);
  border-bottom: 1px solid rgba(204, 204, 204, 1);
  border-left: 3px solid rgba(204, 204, 204, 1);
  white-space: pre-wrap;
  background-color: rgba(245, 245, 245, 1);
}

  .inputWidth {
     width: auto;
 
  }



.edit {
    display: flex;
     height: 300px;
 }
 #leftBox {
     width: 40px; 
     height:100%; 
     text-align:left; 
 }
 #edit-content {
     padding:10px 8px;  
     width:100%; 
     height:100%; 
     font-size: 12px;
     line-height: 24px;
     color: black; 
     font-family: inherit; 
     border:1px solid #eaeaea; 
     background: rgb(255, 255, 255, 1);
     box-sizing: border-box;
     outline:none; 
     resize: none; 
 }
 #leftNum { 
     padding:10px 4px; 
     height:100%; 
     width: 100%; 
     line-height: 24px;
     font-size: 12px; 
     text-align: right; 
     color: #999;
     font-weight: bold; 
     resize: none;
     outline:none; 
     overflow-y: hidden; 
     overflow-x: hidden; 
     border: 0; 
     background:rgba(199, 208, 220, 1);
     box-sizing: border-box;
 }

  .selectWid {
    width: 350px;
  }
 
</style>
